<template>
	<view class="navigator">
		<uv-sticky>
			<uv-tabs :list="sectionList" line-width="20" @change="onSectionChange" :active-style="{
			color: '#E09AB5',
			fontWeight: 'bold',
			transform: 'scale(1.10)'
    	}" line-color="#E09AB5">
				<template v-slot:right>
					<view class="icon-container" @click="goMomentSearch">
						<uv-icon name="search" size="24" bold></uv-icon>
					</view>
				</template>
			</uv-tabs>
		</uv-sticky>
	</view>
	
	<uni-fab 
	:pattern="pattern"
	:content="content" 
	horizontal="right" 
	vertical="bottom" 
	@trigger="trigger"></uni-fab>

	<view class="body">
		<!--
		<unicloud-db v-slot:default="{data, loading, error, options}" collection="pet-post,uni-id-users"
			orderby="publish_date desc" field="title,content,publish_date,user_id{nickname,avatar_file}" loadtime="auto"
			ref="udb">
			<view v-if="error">{{error.message}}</view>
			<view v-else-if="loading"><uv-skeletons :loading="loading" :skeleton="skeleton"></uv-skeletons></view>
			<view v-else>
				<uni-list>
					<uni-list-item v-for="item in data" :title="item.title" :note="item.content"
						:thumb="'https://avataaars.io/?avatarStyle=Circle&topType=LongHairNotTooLong&accessoriesType=Blank&hairColor=Black&facialHairType=Blank&clotheType=BlazerSweater&eyeType=Default&eyebrowType=Default&mouthType=Default&skinColor=Light'"
						ref="post" :rightText="item.user_id[0].nickname"></uni-list-item>
				</uni-list>
			</view>
		</unicloud-db> -->
		<uv-skeletons :loading="loading" :skeleton="skeleton"></uv-skeletons>
		<view v-for="(moment, index) in momentList" :key="index">
			<moment-item :moment="moment"></moment-item>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { computed, ref } from 'vue';
	import { store } from '@/uni_modules/uni-id-pages/common/store.js';
	import { onLoad } from '@dcloudio/uni-app';
	const db = uniCloud.database();
	const userInfo = computed(() => {
		return store.userInfo
	})
	
	let loading = ref(true);

	// Reactive data properties
	const sectionList = ref([{
		name: "推荐"
	}, {
		name: "关注",
		badge: {
			isDot: false
		}
	}]);

	const momentList = ref([]);

	const skeleton = ref([{
		type: 'line',
		num: 5,
		gap: '10rpx',
		style: [
			'width: 200rpx; height: 30rpx; margin: 20rpx', 
			'width: 700rpx; height: 30rpx; margin: 20rpx', 
			'width: 700rpx; height: 30rpx; margin: 20rpx', 
			'width: 700rpx; height: 30rpx; margin: 20rpx', 
			'width: 400rpx; height: 30rpx; margin: 20rpx'],
		// style: 'width: 200rpx;marginBottom: 50rpx;'
		// style: {width: '200rpx',marginBottom: '50rpx'}
	}]);

	//Pattern for the uni-fab(on the bottom-right corner)
	const pattern = ref({
		color: '#7A7E83',
		backgroundColor: '#fff',
		selectedColor: '#007AFF',
		buttonColor: '#E09AB5',
		iconColor: '#fff'
	});
	
	const content = ref([{
						iconPath: '/static/edit.png',
						text: '写帖子',
						active: false
					},
					{
						iconPath: '/static/share.png',
						text: '写文章',
						active: false
					}
				])

	// onLoad lifecycle block
	onLoad(async () => {
		await fetchMoments();
	});

	// Methods	
	const getURL = async () => {
		console.log(this.$refs.post)
		const avatarurl = this.$refs.post.value.avatar_file
		if (avatarurl != null) {
			const avatarRes = await uniCloud.getTempFileURL({ fileList: [avatarurl] });
			return avatarRes.fileList[0].tempFileURL;
		} else {
			return 'https://avataaars.io/?avatarStyle=Circle&topType=LongHairNotTooLong&accessoriesType=Blank&hairColor=Black&facialHairType=Blank&clotheType=BlazerSweater&eyeType=Default&eyebrowType=Default&mouthType=Default&skinColor=Light'
		}

	}
	
	const trigger = (e) => {
			console.log(e)
			if(e.index == 0){
				uni.navigateTo({
					url: '/pages/moments/moments-post/moments-post'
				})
			}else{
				uni.navigateTo({
					url: '/pages/moments/moments-article/moments-article'
				})
			}
		}

	const onSectionChange = (section) => {
		console.log(section);
	};

	const fetchMoments = async () => {
		try {
			const postTemp = db.collection("pet-post").getTemp();
			const userTemp = db.collection("uni-id-users").field("_id, nickname, avatar_file").getTemp();
			const res = await db.collection(postTemp, userTemp).orderBy('publish_date', 'desc').get();
			const posts = res.result.data;
			// Use Promise.all to wait for all promises to resolve
			// TODO: To accelerate the process, this is way too slow. 
			const moments = [];
			for (const post of posts) {
				//获取Avatar的临时地址
				let avatar = "";
				if (post.user_id[0].avatar_file) {
					const avatarurl = post.user_id[0].avatar_file.url;
					const avatarRes = await uniCloud.getTempFileURL({ fileList: [avatarurl] });
					avatar = avatarRes.fileList[0].tempFileURL;
				} else {
					avatar = "https://avataaars.io/?avatarStyle=Circle&topType=LongHairNotTooLong&accessoriesType=Blank&hairColor=Black&facialHairType=Blank&clotheType=BlazerSweater&eyeType=Default&eyebrowType=Default&mouthType=Default&skinColor=Light"
				}
				//获取图片的临时地址
				let images = [];
				if (post.images && post.images.length > 0) {
					const imageRes = await uniCloud.getTempFileURL({ fileList: [...post.images] });
					images = imageRes.fileList.map((e) => e.tempFileURL);
				} else {
					images = [];
				}

				//将数据转换为Moment的内容传递给组件
				const moment = {
					momentInfo: {
						avatar: avatar,
						username: post.user_id[0].nickname,
						publicTime: post.publish_date
					},
					content: {
						title: post.title,
						text: post.content,
						imageList: images
					},
					interactInfo: {
						user_id: post.user_id[0]._id,
						like_count: post.like_count
					}
				};
				moments.push(moment);
			}
			momentList.value = [...momentList.value, ...moments];
			loading = !loading;
		} catch (err) {
			console.log(err);
		}
	};

	const goMomentSearch = () => {
		uni.navigateTo({
			url: '/pages/moments/moments-search/moments-search'
		})
	}
</script>

<style lang="scss" scoped>
	page {
		background: #f5f5f5;
	}

	.navigator {
		margin: 5px;
	}

	.icon-container {
		margin: 10px;
	}

	.edit {
		width: 120rpx;
		height: 120rpx;
		background: #E09AB5;
		border-radius: 50%;
		color: #fff;
		position: fixed;
		z-index: 100;
		bottom: 150rpx;
		right: 50rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		box-shadow: 0 0 20rpx rgba(224, 154, 181, 0.6);
	}
</style>
<link rel="stylesheet" href="lsls.css" />